3 * @defgroup Database Database
5 * This file deals with database interface functions
6 * and query specifics/optimisations.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
26 use Psr\Log\LoggerAwareInterface
;
27 use Psr\Log\LoggerInterface
;
30 * Database abstraction object
33 abstract class DatabaseBase
implements IDatabase
, LoggerAwareInterface
{
34 /** Number of times to re-try an operation in case of deadlock */
35 const DEADLOCK_TRIES
= 4;
36 /** Minimum time to wait before retry, in microseconds */
37 const DEADLOCK_DELAY_MIN
= 500000;
38 /** Maximum time to wait before retry */
39 const DEADLOCK_DELAY_MAX
= 1500000;
41 /** How long before it is worth doing a dummy query to test the connection */
43 const PING_QUERY
= 'SELECT 1 AS ping';
45 const TINY_WRITE_SEC
= .010;
46 const SLOW_WRITE_SEC
= .500;
47 const SMALL_WRITE_ROWS
= 100;
49 /** @var string SQL query */
50 protected $mLastQuery = '';
52 protected $mDoneWrites = false;
53 /** @var string|bool */
54 protected $mPHPError = false;
63 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
64 protected $tableAliases = [];
65 /** @var bool Whether this PHP instance is for a CLI script */
67 /** @var string Agent name for query profiling */
70 /** @var BagOStuff APC cache */
72 /** @var LoggerInterface */
73 protected $connLogger;
74 /** @var LoggerInterface */
75 protected $queryLogger;
76 /** @var callback Error logging callback */
77 protected $errorLogger;
79 /** @var resource Database connection */
80 protected $mConn = null;
82 protected $mOpened = false;
84 /** @var array[] List of (callable, method name) */
85 protected $mTrxIdleCallbacks = [];
86 /** @var array[] List of (callable, method name) */
87 protected $mTrxPreCommitCallbacks = [];
88 /** @var array[] List of (callable, method name) */
89 protected $mTrxEndCallbacks = [];
90 /** @var array[] Map of (name => (callable, method name)) */
91 protected $mTrxRecurringCallbacks = [];
92 /** @var bool Whether to suppress triggering of transaction end callbacks */
93 protected $mTrxEndCallbacksSuppressed = false;
96 protected $mTablePrefix;
102 protected $mLBInfo = [];
103 /** @var bool|null */
104 protected $mDefaultBigSelects = null;
105 /** @var array|bool */
106 protected $mSchemaVars = false;
108 protected $mSessionVars = [];
109 /** @var array|null */
110 protected $preparedArgs;
111 /** @var string|bool|null Stashed value of html_errors INI setting */
112 protected $htmlErrors;
114 protected $delimiter = ';';
117 * Either 1 if a transaction is active or 0 otherwise.
118 * The other Trx fields may not be meaningfull if this is 0.
122 protected $mTrxLevel = 0;
124 * Either a short hexidecimal string if a transaction is active or ""
127 * @see DatabaseBase::mTrxLevel
129 protected $mTrxShortId = '';
131 * The UNIX time that the transaction started. Callers can assume that if
132 * snapshot isolation is used, then the data is *at least* up to date to that
133 * point (possibly more up-to-date since the first SELECT defines the snapshot).
136 * @see DatabaseBase::mTrxLevel
138 private $mTrxTimestamp = null;
139 /** @var float Lag estimate at the time of BEGIN */
140 private $mTrxReplicaLag = null;
142 * Remembers the function name given for starting the most recent transaction via begin().
143 * Used to provide additional context for error reporting.
146 * @see DatabaseBase::mTrxLevel
148 private $mTrxFname = null;
150 * Record if possible write queries were done in the last transaction started
153 * @see DatabaseBase::mTrxLevel
155 private $mTrxDoneWrites = false;
157 * Record if the current transaction was started implicitly due to DBO_TRX being set.
160 * @see DatabaseBase::mTrxLevel
162 private $mTrxAutomatic = false;
164 * Array of levels of atomicity within transactions
168 private $mTrxAtomicLevels = [];
170 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
174 private $mTrxAutomaticAtomic = false;
176 * Track the write query callers of the current transaction
180 private $mTrxWriteCallers = [];
182 * @var float Seconds spent in write queries for the current transaction
184 private $mTrxWriteDuration = 0.0;
186 * @var integer Number of write queries for the current transaction
188 private $mTrxWriteQueryCount = 0;
190 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
192 private $mTrxWriteAdjDuration = 0.0;
194 * @var integer Number of write queries counted in mTrxWriteAdjDuration
196 private $mTrxWriteAdjQueryCount = 0;
198 * @var float RTT time estimate
200 private $mRTTEstimate = 0.0;
202 /** @var array Map of (name => 1) for locks obtained via lock() */
203 private $mNamedLocksHeld = [];
205 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
206 private $lazyMasterHandle;
210 * @var resource File handle for upgrade
212 protected $fileHandle = null;
216 * @var string[] Process cache of VIEWs names in the database
218 protected $allViews = null;
220 /** @var float UNIX timestamp */
221 protected $lastPing = 0.0;
223 /** @var int[] Prior mFlags values */
224 private $priorFlags = [];
228 /** @var TransactionProfiler */
229 protected $trxProfiler;
234 * FIXME: It is possible to construct a Database object with no associated
235 * connection object, by specifying no parameters to __construct(). This
236 * feature is deprecated and should be removed.
238 * IDatabase classes should not be constructed directly in external
239 * code. DatabaseBase::factory() should be used instead.
241 * @param array $params Parameters passed from DatabaseBase::factory()
243 function __construct( array $params ) {
244 $server = $params['host'];
245 $user = $params['user'];
246 $password = $params['password'];
247 $dbName = $params['dbname'];
248 $flags = $params['flags'];
250 $this->mSchema
= $params['schema'];
251 $this->mTablePrefix
= $params['tablePrefix'];
253 $this->cliMode
= isset( $params['cliMode'] )
255 : ( PHP_SAPI
=== 'cli' );
256 $this->agent
= isset( $params['agent'] )
257 ?
str_replace( '/', '-', $params['agent'] ) // escape for comment
260 $this->mFlags
= $flags;
261 if ( $this->mFlags
& DBO_DEFAULT
) {
262 if ( $this->cliMode
) {
263 $this->mFlags
&= ~DBO_TRX
;
265 $this->mFlags |
= DBO_TRX
;
269 $this->mSessionVars
= $params['variables'];
271 $this->srvCache
= isset( $params['srvCache'] )
272 ?
$params['srvCache']
273 : new HashBagOStuff();
275 $this->profiler
= isset( $params['profiler'] )
276 ?
$params['profiler']
277 : Profiler
::instance(); // @TODO: remove global state
278 $this->trxProfiler
= isset( $params['trxProfiler'] )
279 ?
$params['trxProfiler']
280 : new TransactionProfiler();
281 $this->connLogger
= isset( $params['connLogger'] )
282 ?
$params['connLogger']
283 : new \Psr\Log\
NullLogger();
284 $this->queryLogger
= isset( $params['queryLogger'] )
285 ?
$params['queryLogger']
286 : new \Psr\Log\
NullLogger();
289 $this->open( $server, $user, $password, $dbName );
294 * Given a DB type, construct the name of the appropriate child class of
295 * IDatabase. This is designed to replace all of the manual stuff like:
296 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
297 * as well as validate against the canonical list of DB types we have
299 * This factory function is mostly useful for when you need to connect to a
300 * database other than the MediaWiki default (such as for external auth,
301 * an extension, et cetera). Do not use this to connect to the MediaWiki
302 * database. Example uses in core:
303 * @see LoadBalancer::reallyOpenConnection()
304 * @see ForeignDBRepo::getMasterDB()
305 * @see WebInstallerDBConnect::execute()
309 * @param string $dbType A possible DB type
310 * @param array $p An array of options to pass to the constructor.
311 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
312 * @return IDatabase|null If the database driver or extension cannot be found
313 * @throws InvalidArgumentException If the database driver or extension cannot be found
315 final public static function factory( $dbType, $p = [] ) {
316 $canonicalDBTypes = [
317 'mysql' => [ 'mysqli', 'mysql' ],
325 $dbType = strtolower( $dbType );
326 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
327 $possibleDrivers = $canonicalDBTypes[$dbType];
328 if ( !empty( $p['driver'] ) ) {
329 if ( in_array( $p['driver'], $possibleDrivers ) ) {
330 $driver = $p['driver'];
332 throw new InvalidArgumentException( __METHOD__
.
333 " type '$dbType' does not support driver '{$p['driver']}'" );
336 foreach ( $possibleDrivers as $posDriver ) {
337 if ( extension_loaded( $posDriver ) ) {
338 $driver = $posDriver;
346 if ( $driver === false ) {
347 throw new InvalidArgumentException( __METHOD__
.
348 " no viable database extension found for type '$dbType'" );
351 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
352 // and everything else doesn't use a schema (e.g. null)
353 // Although postgres and oracle support schemas, we don't use them (yet)
354 // to maintain backwards compatibility
356 'mssql' => 'get from global',
359 $class = 'Database' . ucfirst( $driver );
360 if ( class_exists( $class ) && is_subclass_of( $class, 'IDatabase' ) ) {
361 // Resolve some defaults for b/c
362 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
363 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
364 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
365 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
366 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
367 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
368 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
369 if ( !isset( $p['schema'] ) ) {
370 $p['schema'] = isset( $defaultSchemas[$dbType] ) ?
$defaultSchemas[$dbType] : null;
372 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
374 $conn = new $class( $p );
375 if ( isset( $p['connLogger'] ) ) {
376 $conn->connLogger
= $p['connLogger'];
378 if ( isset( $p['queryLogger'] ) ) {
379 $conn->queryLogger
= $p['queryLogger'];
381 if ( isset( $p['errorLogger'] ) ) {
382 $conn->errorLogger
= $p['errorLogger'];
384 $conn->errorLogger
= function ( Exception
$e ) {
385 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_WARNING
);
395 public function setLogger( LoggerInterface
$logger ) {
396 $this->queryLogger
= $logger;
399 public function getServerInfo() {
400 return $this->getServerVersion();
404 * @return string Command delimiter used by this database engine
406 public function getDelimiter() {
407 return $this->delimiter
;
411 * Boolean, controls output of large amounts of debug information.
412 * @param bool|null $debug
413 * - true to enable debugging
414 * - false to disable debugging
415 * - omitted or null to do nothing
417 * @return bool|null Previous value of the flag
419 public function debug( $debug = null ) {
420 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
423 public function bufferResults( $buffer = null ) {
424 if ( is_null( $buffer ) ) {
425 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
427 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
432 * Turns on (false) or off (true) the automatic generation and sending
433 * of a "we're sorry, but there has been a database error" page on
434 * database errors. Default is on (false). When turned off, the
435 * code should use lastErrno() and lastError() to handle the
436 * situation as appropriate.
438 * Do not use this function outside of the Database classes.
440 * @param null|bool $ignoreErrors
441 * @return bool The previous value of the flag.
443 protected function ignoreErrors( $ignoreErrors = null ) {
444 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
447 public function trxLevel() {
448 return $this->mTrxLevel
;
451 public function trxTimestamp() {
452 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
455 public function tablePrefix( $prefix = null ) {
456 return wfSetVar( $this->mTablePrefix
, $prefix );
459 public function dbSchema( $schema = null ) {
460 return wfSetVar( $this->mSchema
, $schema );
464 * Set the filehandle to copy write statements to.
466 * @param resource $fh File handle
468 public function setFileHandle( $fh ) {
469 $this->fileHandle
= $fh;
472 public function getLBInfo( $name = null ) {
473 if ( is_null( $name ) ) {
474 return $this->mLBInfo
;
476 if ( array_key_exists( $name, $this->mLBInfo
) ) {
477 return $this->mLBInfo
[$name];
484 public function setLBInfo( $name, $value = null ) {
485 if ( is_null( $value ) ) {
486 $this->mLBInfo
= $name;
488 $this->mLBInfo
[$name] = $value;
492 public function setLazyMasterHandle( IDatabase
$conn ) {
493 $this->lazyMasterHandle
= $conn;
497 * @return IDatabase|null
498 * @see setLazyMasterHandle()
501 public function getLazyMasterHandle() {
502 return $this->lazyMasterHandle
;
506 * @param TransactionProfiler $profiler
509 public function setTransactionProfiler( TransactionProfiler
$profiler ) {
510 $this->trxProfiler
= $profiler;
514 * Returns true if this database supports (and uses) cascading deletes
518 public function cascadingDeletes() {
523 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
527 public function cleanupTriggers() {
532 * Returns true if this database is strict about what can be put into an IP field.
533 * Specifically, it uses a NULL value instead of an empty string.
537 public function strictIPs() {
542 * Returns true if this database uses timestamps rather than integers
546 public function realTimestamps() {
550 public function implicitGroupby() {
554 public function implicitOrderby() {
559 * Returns true if this database can do a native search on IP columns
560 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
564 public function searchableIPs() {
569 * Returns true if this database can use functional indexes
573 public function functionalIndexes() {
577 public function lastQuery() {
578 return $this->mLastQuery
;
581 public function doneWrites() {
582 return (bool)$this->mDoneWrites
;
585 public function lastDoneWrites() {
586 return $this->mDoneWrites ?
: false;
589 public function writesPending() {
590 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
593 public function writesOrCallbacksPending() {
594 return $this->mTrxLevel
&& (
595 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
599 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
600 if ( !$this->mTrxLevel
) {
602 } elseif ( !$this->mTrxDoneWrites
) {
607 case self
::ESTIMATE_DB_APPLY
:
609 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
610 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
611 // For omitted queries, make them count as something at least
612 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
613 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
616 default: // everything
617 return $this->mTrxWriteDuration
;
621 public function pendingWriteCallers() {
622 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
625 public function isOpen() {
626 return $this->mOpened
;
629 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
630 if ( $remember === self
::REMEMBER_PRIOR
) {
631 array_push( $this->priorFlags
, $this->mFlags
);
633 $this->mFlags |
= $flag;
636 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
637 if ( $remember === self
::REMEMBER_PRIOR
) {
638 array_push( $this->priorFlags
, $this->mFlags
);
640 $this->mFlags
&= ~
$flag;
643 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
644 if ( !$this->priorFlags
) {
648 if ( $state === self
::RESTORE_INITIAL
) {
649 $this->mFlags
= reset( $this->priorFlags
);
650 $this->priorFlags
= [];
652 $this->mFlags
= array_pop( $this->priorFlags
);
656 public function getFlag( $flag ) {
657 return !!( $this->mFlags
& $flag );
660 public function getProperty( $name ) {
664 public function getWikiID() {
665 if ( $this->mTablePrefix
) {
666 return "{$this->mDBname}-{$this->mTablePrefix}";
668 return $this->mDBname
;
673 * Get information about an index into an object
674 * @param string $table Table name
675 * @param string $index Index name
676 * @param string $fname Calling function name
677 * @return mixed Database-specific index description class or false if the index does not exist
679 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
682 * Wrapper for addslashes()
684 * @param string $s String to be slashed.
685 * @return string Slashed string.
687 abstract function strencode( $s );
690 * Called by serialize. Throw an exception when DB connection is serialized.
691 * This causes problems on some database engines because the connection is
692 * not restored on unserialize.
694 public function __sleep() {
695 throw new RuntimeException( 'Database serialization may cause problems, since ' .
696 'the connection is not restored on wakeup.' );
699 protected function installErrorHandler() {
700 $this->mPHPError
= false;
701 $this->htmlErrors
= ini_set( 'html_errors', '0' );
702 set_error_handler( [ $this, 'connectionerrorLogger' ] );
706 * @return bool|string
708 protected function restoreErrorHandler() {
709 restore_error_handler();
710 if ( $this->htmlErrors
!== false ) {
711 ini_set( 'html_errors', $this->htmlErrors
);
713 if ( $this->mPHPError
) {
714 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
715 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
725 * @param string $errstr
727 public function connectionerrorLogger( $errno, $errstr ) {
728 $this->mPHPError
= $errstr;
732 * Create a log context to pass to PSR logging functions.
734 * @param array $extras Additional data to add to context
737 protected function getLogContext( array $extras = [] ) {
740 'db_server' => $this->mServer
,
741 'db_name' => $this->mDBname
,
742 'db_user' => $this->mUser
,
748 public function close() {
749 if ( $this->mConn
) {
750 if ( $this->trxLevel() ) {
751 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
754 $closed = $this->closeConnection();
755 $this->mConn
= false;
756 } elseif ( $this->mTrxIdleCallbacks ||
$this->mTrxEndCallbacks
) { // sanity
757 throw new RuntimeException( "Transaction callbacks still pending." );
761 $this->mOpened
= false;
767 * Make sure isOpen() returns true as a sanity check
769 * @throws DBUnexpectedError
771 protected function assertOpen() {
772 if ( !$this->isOpen() ) {
773 throw new DBUnexpectedError( $this, "DB connection was already closed." );
778 * Closes underlying database connection
780 * @return bool Whether connection was closed successfully
782 abstract protected function closeConnection();
784 function reportConnectionError( $error = 'Unknown error' ) {
785 $myError = $this->lastError();
791 throw new DBConnectionError( $this, $error );
795 * The DBMS-dependent part of query()
797 * @param string $sql SQL query.
798 * @return ResultWrapper|bool Result object to feed to fetchObject,
799 * fetchRow, ...; or false on failure
801 abstract protected function doQuery( $sql );
804 * Determine whether a query writes to the DB.
805 * Should return true if unsure.
810 protected function isWriteQuery( $sql ) {
812 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
817 * @return string|null
819 protected function getQueryVerb( $sql ) {
820 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
824 * Determine whether a SQL statement is sensitive to isolation level.
825 * A SQL statement is considered transactable if its result could vary
826 * depending on the transaction isolation level. Operational commands
827 * such as 'SET' and 'SHOW' are not considered to be transactable.
832 protected function isTransactableQuery( $sql ) {
833 $verb = $this->getQueryVerb( $sql );
834 return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ], true );
837 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
838 $priorWritesPending = $this->writesOrCallbacksPending();
839 $this->mLastQuery
= $sql;
841 $isWrite = $this->isWriteQuery( $sql );
843 $reason = $this->getReadOnlyReason();
844 if ( $reason !== false ) {
845 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
847 # Set a flag indicating that writes have been done
848 $this->mDoneWrites
= microtime( true );
851 // Add trace comment to the begin of the sql string, right after the operator.
852 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
853 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
855 # Start implicit transactions that wrap the request if DBO_TRX is enabled
856 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
)
857 && $this->isTransactableQuery( $sql )
859 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
860 $this->mTrxAutomatic
= true;
863 # Keep track of whether the transaction has write queries pending
864 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
865 $this->mTrxDoneWrites
= true;
866 $this->trxProfiler
->transactionWritingIn(
867 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
870 if ( $this->debug() ) {
871 $this->queryLogger
->debug( "{$this->mDBname} {$commentedSql}" );
874 # Avoid fatals if close() was called
877 # Send the query to the server
878 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
880 # Try reconnecting if the connection was lost
881 if ( false === $ret && $this->wasErrorReissuable() ) {
882 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
883 # Stash the last error values before anything might clear them
884 $lastError = $this->lastError();
885 $lastErrno = $this->lastErrno();
886 # Update state tracking to reflect transaction loss due to disconnection
887 $this->handleTransactionLoss();
888 if ( $this->reconnect() ) {
889 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
890 $this->connLogger
->warning( $msg );
891 $this->queryLogger
->warning(
892 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
894 if ( !$recoverable ) {
895 # Callers may catch the exception and continue to use the DB
896 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
898 # Should be safe to silently retry the query
899 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
902 $msg = __METHOD__
. ": lost connection to {$this->getServer()} permanently";
903 $this->connLogger
->error( $msg );
907 if ( false === $ret ) {
908 # Deadlocks cause the entire transaction to abort, not just the statement.
909 # http://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
910 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
911 if ( $this->wasDeadlock() ) {
912 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
913 $tempIgnore = false; // not recoverable
915 # Update state tracking to reflect transaction loss
916 $this->handleTransactionLoss();
919 $this->reportQueryError(
920 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
923 $res = $this->resultObject( $ret );
928 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
929 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
930 # generalizeSQL() will probably cut down the query to reasonable
931 # logging size most of the time. The substr is really just a sanity check.
933 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
935 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
938 # Include query transaction state
939 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
941 $startTime = microtime( true );
942 $this->profiler
->profileIn( $queryProf );
943 $ret = $this->doQuery( $commentedSql );
944 $this->profiler
->profileOut( $queryProf );
945 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
947 unset( $queryProfSection ); // profile out (if set)
949 if ( $ret !== false ) {
950 $this->lastPing
= $startTime;
951 if ( $isWrite && $this->mTrxLevel
) {
952 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
953 $this->mTrxWriteCallers
[] = $fname;
957 if ( $sql === self
::PING_QUERY
) {
958 $this->mRTTEstimate
= $queryRuntime;
961 $this->trxProfiler
->recordQueryCompletion(
962 $queryProf, $startTime, $isWrite, $this->affectedRows()
964 MWDebug
::query( $sql, $fname, $isMaster, $queryRuntime );
970 * Update the estimated run-time of a query, not counting large row lock times
972 * LoadBalancer can be set to rollback transactions that will create huge replication
973 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
974 * queries, like inserting a row can take a long time due to row locking. This method
975 * uses some simple heuristics to discount those cases.
977 * @param string $sql A SQL write query
978 * @param float $runtime Total runtime, including RTT
980 private function updateTrxWriteQueryTime( $sql, $runtime ) {
981 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
982 $indicativeOfReplicaRuntime = true;
983 if ( $runtime > self
::SLOW_WRITE_SEC
) {
984 $verb = $this->getQueryVerb( $sql );
985 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
986 if ( $verb === 'INSERT' ) {
987 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
988 } elseif ( $verb === 'REPLACE' ) {
989 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
993 $this->mTrxWriteDuration +
= $runtime;
994 $this->mTrxWriteQueryCount +
= 1;
995 if ( $indicativeOfReplicaRuntime ) {
996 $this->mTrxWriteAdjDuration +
= $runtime;
997 $this->mTrxWriteAdjQueryCount +
= 1;
1001 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1002 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1003 # Dropped connections also mean that named locks are automatically released.
1004 # Only allow error suppression in autocommit mode or when the lost transaction
1005 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1006 if ( $this->mNamedLocksHeld
) {
1007 return false; // possible critical section violation
1008 } elseif ( $sql === 'COMMIT' ) {
1009 return !$priorWritesPending; // nothing written anyway? (T127428)
1010 } elseif ( $sql === 'ROLLBACK' ) {
1011 return true; // transaction lost...which is also what was requested :)
1012 } elseif ( $this->explicitTrxActive() ) {
1013 return false; // don't drop atomocity
1014 } elseif ( $priorWritesPending ) {
1015 return false; // prior writes lost from implicit transaction
1021 private function handleTransactionLoss() {
1022 $this->mTrxLevel
= 0;
1023 $this->mTrxIdleCallbacks
= []; // bug 65263
1024 $this->mTrxPreCommitCallbacks
= []; // bug 65263
1026 // Handle callbacks in mTrxEndCallbacks
1027 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1028 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1030 } catch ( Exception
$e ) {
1031 // Already logged; move on...
1036 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1037 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1038 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1040 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1041 $this->queryLogger
->error(
1042 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1043 $this->getLogContext( [
1044 'method' => __METHOD__
,
1047 'sql1line' => $sql1line,
1051 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1052 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1057 * Intended to be compatible with the PEAR::DB wrapper functions.
1058 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1060 * ? = scalar value, quoted as necessary
1061 * ! = raw SQL bit (a function for instance)
1062 * & = filename; reads the file and inserts as a blob
1063 * (we don't use this though...)
1065 * @param string $sql
1066 * @param string $func
1070 protected function prepare( $sql, $func = __METHOD__
) {
1071 /* MySQL doesn't support prepared statements (yet), so just
1072 * pack up the query for reference. We'll manually replace
1075 return [ 'query' => $sql, 'func' => $func ];
1079 * Free a prepared query, generated by prepare().
1080 * @param string $prepared
1082 protected function freePrepared( $prepared ) {
1083 /* No-op by default */
1087 * Execute a prepared query with the various arguments
1088 * @param string $prepared The prepared sql
1089 * @param mixed $args Either an array here, or put scalars as varargs
1091 * @return ResultWrapper
1093 public function execute( $prepared, $args = null ) {
1094 if ( !is_array( $args ) ) {
1096 $args = func_get_args();
1097 array_shift( $args );
1100 $sql = $this->fillPrepared( $prepared['query'], $args );
1102 return $this->query( $sql, $prepared['func'] );
1106 * For faking prepared SQL statements on DBs that don't support it directly.
1108 * @param string $preparedQuery A 'preparable' SQL statement
1109 * @param array $args Array of Arguments to fill it with
1110 * @return string Executable SQL
1112 public function fillPrepared( $preparedQuery, $args ) {
1114 $this->preparedArgs
=& $args;
1116 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1117 [ &$this, 'fillPreparedArg' ], $preparedQuery );
1121 * preg_callback func for fillPrepared()
1122 * The arguments should be in $this->preparedArgs and must not be touched
1123 * while we're doing this.
1125 * @param array $matches
1126 * @throws DBUnexpectedError
1129 protected function fillPreparedArg( $matches ) {
1130 switch ( $matches[1] ) {
1139 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1141 switch ( $matches[1] ) {
1143 return $this->addQuotes( $arg );
1147 # return $this->addQuotes( file_get_contents( $arg ) );
1148 throw new DBUnexpectedError(
1150 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1153 throw new DBUnexpectedError(
1155 'Received invalid match. This should never happen!'
1160 public function freeResult( $res ) {
1163 public function selectField(
1164 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1166 if ( $var === '*' ) { // sanity
1167 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1170 if ( !is_array( $options ) ) {
1171 $options = [ $options ];
1174 $options['LIMIT'] = 1;
1176 $res = $this->select( $table, $var, $cond, $fname, $options );
1177 if ( $res === false ||
!$this->numRows( $res ) ) {
1181 $row = $this->fetchRow( $res );
1183 if ( $row !== false ) {
1184 return reset( $row );
1190 public function selectFieldValues(
1191 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1193 if ( $var === '*' ) { // sanity
1194 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1195 } elseif ( !is_string( $var ) ) { // sanity
1196 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1199 if ( !is_array( $options ) ) {
1200 $options = [ $options ];
1203 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1204 if ( $res === false ) {
1209 foreach ( $res as $row ) {
1210 $values[] = $row->$var;
1217 * Returns an optional USE INDEX clause to go after the table, and a
1218 * string to go at the end of the query.
1220 * @param array $options Associative array of options to be turned into
1221 * an SQL query, valid keys are listed in the function.
1223 * @see DatabaseBase::select()
1225 public function makeSelectOptions( $options ) {
1226 $preLimitTail = $postLimitTail = '';
1231 foreach ( $options as $key => $option ) {
1232 if ( is_numeric( $key ) ) {
1233 $noKeyOptions[$option] = true;
1237 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1239 $preLimitTail .= $this->makeOrderBy( $options );
1241 // if (isset($options['LIMIT'])) {
1242 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1243 // isset($options['OFFSET']) ? $options['OFFSET']
1247 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1248 $postLimitTail .= ' FOR UPDATE';
1251 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1252 $postLimitTail .= ' LOCK IN SHARE MODE';
1255 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1256 $startOpts .= 'DISTINCT';
1259 # Various MySQL extensions
1260 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1261 $startOpts .= ' /*! STRAIGHT_JOIN */';
1264 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1265 $startOpts .= ' HIGH_PRIORITY';
1268 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1269 $startOpts .= ' SQL_BIG_RESULT';
1272 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1273 $startOpts .= ' SQL_BUFFER_RESULT';
1276 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1277 $startOpts .= ' SQL_SMALL_RESULT';
1280 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1281 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1284 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1285 $startOpts .= ' SQL_CACHE';
1288 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1289 $startOpts .= ' SQL_NO_CACHE';
1292 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1293 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1297 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1298 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1303 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1307 * Returns an optional GROUP BY with an optional HAVING
1309 * @param array $options Associative array of options
1311 * @see DatabaseBase::select()
1314 public function makeGroupByWithHaving( $options ) {
1316 if ( isset( $options['GROUP BY'] ) ) {
1317 $gb = is_array( $options['GROUP BY'] )
1318 ?
implode( ',', $options['GROUP BY'] )
1319 : $options['GROUP BY'];
1320 $sql .= ' GROUP BY ' . $gb;
1322 if ( isset( $options['HAVING'] ) ) {
1323 $having = is_array( $options['HAVING'] )
1324 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1325 : $options['HAVING'];
1326 $sql .= ' HAVING ' . $having;
1333 * Returns an optional ORDER BY
1335 * @param array $options Associative array of options
1337 * @see DatabaseBase::select()
1340 public function makeOrderBy( $options ) {
1341 if ( isset( $options['ORDER BY'] ) ) {
1342 $ob = is_array( $options['ORDER BY'] )
1343 ?
implode( ',', $options['ORDER BY'] )
1344 : $options['ORDER BY'];
1346 return ' ORDER BY ' . $ob;
1352 // See IDatabase::select for the docs for this function
1353 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1354 $options = [], $join_conds = [] ) {
1355 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1357 return $this->query( $sql, $fname );
1360 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1361 $options = [], $join_conds = []
1363 if ( is_array( $vars ) ) {
1364 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1367 $options = (array)$options;
1368 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1369 ?
$options['USE INDEX']
1371 $ignoreIndexes = ( isset( $options['IGNORE INDEX'] ) && is_array( $options['IGNORE INDEX'] ) )
1372 ?
$options['IGNORE INDEX']
1375 if ( is_array( $table ) ) {
1377 $this->tableNamesWithIndexClauseOrJOIN( $table, $useIndexes, $ignoreIndexes, $join_conds );
1378 } elseif ( $table != '' ) {
1379 if ( $table[0] == ' ' ) {
1380 $from = ' FROM ' . $table;
1383 $this->tableNamesWithIndexClauseOrJOIN( [ $table ], $useIndexes, $ignoreIndexes, [] );
1389 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1390 $this->makeSelectOptions( $options );
1392 if ( !empty( $conds ) ) {
1393 if ( is_array( $conds ) ) {
1394 $conds = $this->makeList( $conds, LIST_AND
);
1396 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex WHERE $conds $preLimitTail";
1398 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1401 if ( isset( $options['LIMIT'] ) ) {
1402 $sql = $this->limitResult( $sql, $options['LIMIT'],
1403 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1405 $sql = "$sql $postLimitTail";
1407 if ( isset( $options['EXPLAIN'] ) ) {
1408 $sql = 'EXPLAIN ' . $sql;
1414 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1415 $options = [], $join_conds = []
1417 $options = (array)$options;
1418 $options['LIMIT'] = 1;
1419 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1421 if ( $res === false ) {
1425 if ( !$this->numRows( $res ) ) {
1429 $obj = $this->fetchObject( $res );
1434 public function estimateRowCount(
1435 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1438 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1441 $row = $this->fetchRow( $res );
1442 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1448 public function selectRowCount(
1449 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1452 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1453 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1456 $row = $this->fetchRow( $res );
1457 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1464 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1465 * It's only slightly flawed. Don't use for anything important.
1467 * @param string $sql A SQL Query
1471 protected static function generalizeSQL( $sql ) {
1472 # This does the same as the regexp below would do, but in such a way
1473 # as to avoid crashing php on some large strings.
1474 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1476 $sql = str_replace( "\\\\", '', $sql );
1477 $sql = str_replace( "\\'", '', $sql );
1478 $sql = str_replace( "\\\"", '', $sql );
1479 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1480 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1482 # All newlines, tabs, etc replaced by single space
1483 $sql = preg_replace( '/\s+/', ' ', $sql );
1486 # except the ones surrounded by characters, e.g. l10n
1487 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1488 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1493 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1494 $info = $this->fieldInfo( $table, $field );
1499 public function indexExists( $table, $index, $fname = __METHOD__
) {
1500 if ( !$this->tableExists( $table ) ) {
1504 $info = $this->indexInfo( $table, $index, $fname );
1505 if ( is_null( $info ) ) {
1508 return $info !== false;
1512 public function tableExists( $table, $fname = __METHOD__
) {
1513 $table = $this->tableName( $table );
1514 $old = $this->ignoreErrors( true );
1515 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1516 $this->ignoreErrors( $old );
1521 public function indexUnique( $table, $index ) {
1522 $indexInfo = $this->indexInfo( $table, $index );
1524 if ( !$indexInfo ) {
1528 return !$indexInfo[0]->Non_unique
;
1532 * Helper for DatabaseBase::insert().
1534 * @param array $options
1537 protected function makeInsertOptions( $options ) {
1538 return implode( ' ', $options );
1541 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1542 # No rows to insert, easy just return now
1543 if ( !count( $a ) ) {
1547 $table = $this->tableName( $table );
1549 if ( !is_array( $options ) ) {
1550 $options = [ $options ];
1554 if ( isset( $options['fileHandle'] ) ) {
1555 $fh = $options['fileHandle'];
1557 $options = $this->makeInsertOptions( $options );
1559 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1561 $keys = array_keys( $a[0] );
1564 $keys = array_keys( $a );
1567 $sql = 'INSERT ' . $options .
1568 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1572 foreach ( $a as $row ) {
1578 $sql .= '(' . $this->makeList( $row ) . ')';
1581 $sql .= '(' . $this->makeList( $a ) . ')';
1584 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1586 } elseif ( $fh !== null ) {
1590 return (bool)$this->query( $sql, $fname );
1594 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1596 * @param array $options
1599 protected function makeUpdateOptionsArray( $options ) {
1600 if ( !is_array( $options ) ) {
1601 $options = [ $options ];
1606 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1607 $opts[] = $this->lowPriorityOption();
1610 if ( in_array( 'IGNORE', $options ) ) {
1618 * Make UPDATE options for the DatabaseBase::update function
1620 * @param array $options The options passed to DatabaseBase::update
1623 protected function makeUpdateOptions( $options ) {
1624 $opts = $this->makeUpdateOptionsArray( $options );
1626 return implode( ' ', $opts );
1629 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1630 $table = $this->tableName( $table );
1631 $opts = $this->makeUpdateOptions( $options );
1632 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1634 if ( $conds !== [] && $conds !== '*' ) {
1635 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1638 return $this->query( $sql, $fname );
1641 public function makeList( $a, $mode = LIST_COMMA
) {
1642 if ( !is_array( $a ) ) {
1643 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1649 foreach ( $a as $field => $value ) {
1651 if ( $mode == LIST_AND
) {
1653 } elseif ( $mode == LIST_OR
) {
1662 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1663 $list .= "($value)";
1664 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1666 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1667 // Remove null from array to be handled separately if found
1668 $includeNull = false;
1669 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1670 $includeNull = true;
1671 unset( $value[$nullKey] );
1673 if ( count( $value ) == 0 && !$includeNull ) {
1674 throw new InvalidArgumentException( __METHOD__
. ": empty input for field $field" );
1675 } elseif ( count( $value ) == 0 ) {
1676 // only check if $field is null
1677 $list .= "$field IS NULL";
1679 // IN clause contains at least one valid element
1680 if ( $includeNull ) {
1681 // Group subconditions to ensure correct precedence
1684 if ( count( $value ) == 1 ) {
1685 // Special-case single values, as IN isn't terribly efficient
1686 // Don't necessarily assume the single key is 0; we don't
1687 // enforce linear numeric ordering on other arrays here.
1688 $value = array_values( $value )[0];
1689 $list .= $field . " = " . $this->addQuotes( $value );
1691 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1693 // if null present in array, append IS NULL
1694 if ( $includeNull ) {
1695 $list .= " OR $field IS NULL)";
1698 } elseif ( $value === null ) {
1699 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1700 $list .= "$field IS ";
1701 } elseif ( $mode == LIST_SET
) {
1702 $list .= "$field = ";
1706 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1707 $list .= "$field = ";
1709 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1716 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1719 foreach ( $data as $base => $sub ) {
1720 if ( count( $sub ) ) {
1721 $conds[] = $this->makeList(
1722 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1728 return $this->makeList( $conds, LIST_OR
);
1730 // Nothing to search for...
1736 * Return aggregated value alias
1738 * @param array $valuedata
1739 * @param string $valuename
1743 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1747 public function bitNot( $field ) {
1751 public function bitAnd( $fieldLeft, $fieldRight ) {
1752 return "($fieldLeft & $fieldRight)";
1755 public function bitOr( $fieldLeft, $fieldRight ) {
1756 return "($fieldLeft | $fieldRight)";
1759 public function buildConcat( $stringList ) {
1760 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1763 public function buildGroupConcatField(
1764 $delim, $table, $field, $conds = '', $join_conds = []
1766 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1768 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1772 * @param string $field Field or column to cast
1776 public function buildStringCast( $field ) {
1780 public function selectDB( $db ) {
1781 # Stub. Shouldn't cause serious problems if it's not overridden, but
1782 # if your database engine supports a concept similar to MySQL's
1783 # databases you may as well.
1784 $this->mDBname
= $db;
1789 public function getDBname() {
1790 return $this->mDBname
;
1793 public function getServer() {
1794 return $this->mServer
;
1798 * Format a table name ready for use in constructing an SQL query
1800 * This does two important things: it quotes the table names to clean them up,
1801 * and it adds a table prefix if only given a table name with no quotes.
1803 * All functions of this object which require a table name call this function
1804 * themselves. Pass the canonical name to such functions. This is only needed
1805 * when calling query() directly.
1807 * @note This function does not sanitize user input. It is not safe to use
1808 * this function to escape user input.
1809 * @param string $name Database table name
1810 * @param string $format One of:
1811 * quoted - Automatically pass the table name through addIdentifierQuotes()
1812 * so that it can be used in a query.
1813 * raw - Do not add identifier quotes to the table name
1814 * @return string Full database name
1816 public function tableName( $name, $format = 'quoted' ) {
1817 # Skip the entire process when we have a string quoted on both ends.
1818 # Note that we check the end so that we will still quote any use of
1819 # use of `database`.table. But won't break things if someone wants
1820 # to query a database table with a dot in the name.
1821 if ( $this->isQuotedIdentifier( $name ) ) {
1825 # Lets test for any bits of text that should never show up in a table
1826 # name. Basically anything like JOIN or ON which are actually part of
1827 # SQL queries, but may end up inside of the table value to combine
1828 # sql. Such as how the API is doing.
1829 # Note that we use a whitespace test rather than a \b test to avoid
1830 # any remote case where a word like on may be inside of a table name
1831 # surrounded by symbols which may be considered word breaks.
1832 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1836 # Split database and table into proper variables.
1837 # We reverse the explode so that database.table and table both output
1838 # the correct table.
1839 $dbDetails = explode( '.', $name, 3 );
1840 if ( count( $dbDetails ) == 3 ) {
1841 list( $database, $schema, $table ) = $dbDetails;
1842 # We don't want any prefix added in this case
1844 } elseif ( count( $dbDetails ) == 2 ) {
1845 list( $database, $table ) = $dbDetails;
1846 # We don't want any prefix added in this case
1847 # In dbs that support it, $database may actually be the schema
1848 # but that doesn't affect any of the functionality here
1852 list( $table ) = $dbDetails;
1853 if ( isset( $this->tableAliases
[$table] ) ) {
1854 $database = $this->tableAliases
[$table]['dbname'];
1855 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1856 ?
$this->tableAliases
[$table]['schema']
1858 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1859 ?
$this->tableAliases
[$table]['prefix']
1860 : $this->mTablePrefix
;
1863 $schema = $this->mSchema
; # Default schema
1864 $prefix = $this->mTablePrefix
; # Default prefix
1868 # Quote $table and apply the prefix if not quoted.
1869 # $tableName might be empty if this is called from Database::replaceVars()
1870 $tableName = "{$prefix}{$table}";
1871 if ( $format == 'quoted'
1872 && !$this->isQuotedIdentifier( $tableName ) && $tableName !== ''
1874 $tableName = $this->addIdentifierQuotes( $tableName );
1877 # Quote $schema and merge it with the table name if needed
1878 if ( strlen( $schema ) ) {
1879 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1880 $schema = $this->addIdentifierQuotes( $schema );
1882 $tableName = $schema . '.' . $tableName;
1885 # Quote $database and merge it with the table name if needed
1886 if ( $database !== null ) {
1887 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1888 $database = $this->addIdentifierQuotes( $database );
1890 $tableName = $database . '.' . $tableName;
1897 * Fetch a number of table names into an array
1898 * This is handy when you need to construct SQL for joins
1901 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1902 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1903 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1907 public function tableNames() {
1908 $inArray = func_get_args();
1911 foreach ( $inArray as $name ) {
1912 $retVal[$name] = $this->tableName( $name );
1919 * Fetch a number of table names into an zero-indexed numerical array
1920 * This is handy when you need to construct SQL for joins
1923 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1924 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1925 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1929 public function tableNamesN() {
1930 $inArray = func_get_args();
1933 foreach ( $inArray as $name ) {
1934 $retVal[] = $this->tableName( $name );
1941 * Get an aliased table name
1942 * e.g. tableName AS newTableName
1944 * @param string $name Table name, see tableName()
1945 * @param string|bool $alias Alias (optional)
1946 * @return string SQL name for aliased table. Will not alias a table to its own name
1948 public function tableNameWithAlias( $name, $alias = false ) {
1949 if ( !$alias ||
$alias == $name ) {
1950 return $this->tableName( $name );
1952 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1957 * Gets an array of aliased table names
1959 * @param array $tables [ [alias] => table ]
1960 * @return string[] See tableNameWithAlias()
1962 public function tableNamesWithAlias( $tables ) {
1964 foreach ( $tables as $alias => $table ) {
1965 if ( is_numeric( $alias ) ) {
1968 $retval[] = $this->tableNameWithAlias( $table, $alias );
1975 * Get an aliased field name
1976 * e.g. fieldName AS newFieldName
1978 * @param string $name Field name
1979 * @param string|bool $alias Alias (optional)
1980 * @return string SQL name for aliased field. Will not alias a field to its own name
1982 public function fieldNameWithAlias( $name, $alias = false ) {
1983 if ( !$alias ||
(string)$alias === (string)$name ) {
1986 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1991 * Gets an array of aliased field names
1993 * @param array $fields [ [alias] => field ]
1994 * @return string[] See fieldNameWithAlias()
1996 public function fieldNamesWithAlias( $fields ) {
1998 foreach ( $fields as $alias => $field ) {
1999 if ( is_numeric( $alias ) ) {
2002 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2009 * Get the aliased table name clause for a FROM clause
2010 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2012 * @param array $tables ( [alias] => table )
2013 * @param array $use_index Same as for select()
2014 * @param array $ignore_index Same as for select()
2015 * @param array $join_conds Same as for select()
2018 protected function tableNamesWithIndexClauseOrJOIN(
2019 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2023 $use_index = (array)$use_index;
2024 $ignore_index = (array)$ignore_index;
2025 $join_conds = (array)$join_conds;
2027 foreach ( $tables as $alias => $table ) {
2028 if ( !is_string( $alias ) ) {
2029 // No alias? Set it equal to the table name
2032 // Is there a JOIN clause for this table?
2033 if ( isset( $join_conds[$alias] ) ) {
2034 list( $joinType, $conds ) = $join_conds[$alias];
2035 $tableClause = $joinType;
2036 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2037 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2038 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2040 $tableClause .= ' ' . $use;
2043 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2044 $ignore = $this->ignoreIndexClause( implode( ',', (array)$ignore_index[$alias] ) );
2045 if ( $ignore != '' ) {
2046 $tableClause .= ' ' . $ignore;
2049 $on = $this->makeList( (array)$conds, LIST_AND
);
2051 $tableClause .= ' ON (' . $on . ')';
2054 $retJOIN[] = $tableClause;
2055 } elseif ( isset( $use_index[$alias] ) ) {
2056 // Is there an INDEX clause for this table?
2057 $tableClause = $this->tableNameWithAlias( $table, $alias );
2058 $tableClause .= ' ' . $this->useIndexClause(
2059 implode( ',', (array)$use_index[$alias] )
2062 $ret[] = $tableClause;
2063 } elseif ( isset( $ignore_index[$alias] ) ) {
2064 // Is there an INDEX clause for this table?
2065 $tableClause = $this->tableNameWithAlias( $table, $alias );
2066 $tableClause .= ' ' . $this->ignoreIndexClause(
2067 implode( ',', (array)$ignore_index[$alias] )
2070 $ret[] = $tableClause;
2072 $tableClause = $this->tableNameWithAlias( $table, $alias );
2074 $ret[] = $tableClause;
2078 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2079 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2080 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2082 // Compile our final table clause
2083 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2087 * Get the name of an index in a given table.
2089 * @param string $index
2092 protected function indexName( $index ) {
2093 // Backwards-compatibility hack
2095 'ar_usertext_timestamp' => 'usertext_timestamp',
2096 'un_user_id' => 'user_id',
2097 'un_user_ip' => 'user_ip',
2100 if ( isset( $renamed[$index] ) ) {
2101 return $renamed[$index];
2107 public function addQuotes( $s ) {
2108 if ( $s instanceof Blob
) {
2111 if ( $s === null ) {
2114 # This will also quote numeric values. This should be harmless,
2115 # and protects against weird problems that occur when they really
2116 # _are_ strings such as article titles and string->number->string
2117 # conversion is not 1:1.
2118 return "'" . $this->strencode( $s ) . "'";
2123 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2124 * MySQL uses `backticks` while basically everything else uses double quotes.
2125 * Since MySQL is the odd one out here the double quotes are our generic
2126 * and we implement backticks in DatabaseMysql.
2131 public function addIdentifierQuotes( $s ) {
2132 return '"' . str_replace( '"', '""', $s ) . '"';
2136 * Returns if the given identifier looks quoted or not according to
2137 * the database convention for quoting identifiers .
2139 * @note Do not use this to determine if untrusted input is safe.
2140 * A malicious user can trick this function.
2141 * @param string $name
2144 public function isQuotedIdentifier( $name ) {
2145 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2152 protected function escapeLikeInternal( $s ) {
2153 return addcslashes( $s, '\%_' );
2156 public function buildLike() {
2157 $params = func_get_args();
2159 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2160 $params = $params[0];
2165 foreach ( $params as $value ) {
2166 if ( $value instanceof LikeMatch
) {
2167 $s .= $value->toString();
2169 $s .= $this->escapeLikeInternal( $value );
2173 return " LIKE {$this->addQuotes( $s )} ";
2176 public function anyChar() {
2177 return new LikeMatch( '_' );
2180 public function anyString() {
2181 return new LikeMatch( '%' );
2184 public function nextSequenceValue( $seqName ) {
2189 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2190 * is only needed because a) MySQL must be as efficient as possible due to
2191 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2192 * which index to pick. Anyway, other databases might have different
2193 * indexes on a given table. So don't bother overriding this unless you're
2195 * @param string $index
2198 public function useIndexClause( $index ) {
2203 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2204 * is only needed because a) MySQL must be as efficient as possible due to
2205 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2206 * which index to pick. Anyway, other databases might have different
2207 * indexes on a given table. So don't bother overriding this unless you're
2209 * @param string $index
2212 public function ignoreIndexClause( $index ) {
2216 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2217 $quotedTable = $this->tableName( $table );
2219 if ( count( $rows ) == 0 ) {
2224 if ( !is_array( reset( $rows ) ) ) {
2228 // @FXIME: this is not atomic, but a trx would break affectedRows()
2229 foreach ( $rows as $row ) {
2230 # Delete rows which collide
2231 if ( $uniqueIndexes ) {
2232 $sql = "DELETE FROM $quotedTable WHERE ";
2234 foreach ( $uniqueIndexes as $index ) {
2241 if ( is_array( $index ) ) {
2243 foreach ( $index as $col ) {
2249 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2252 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2256 $this->query( $sql, $fname );
2259 # Now insert the row
2260 $this->insert( $table, $row, $fname );
2265 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2268 * @param string $table Table name
2269 * @param array|string $rows Row(s) to insert
2270 * @param string $fname Caller function name
2272 * @return ResultWrapper
2274 protected function nativeReplace( $table, $rows, $fname ) {
2275 $table = $this->tableName( $table );
2278 if ( !is_array( reset( $rows ) ) ) {
2282 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2285 foreach ( $rows as $row ) {
2292 $sql .= '(' . $this->makeList( $row ) . ')';
2295 return $this->query( $sql, $fname );
2298 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2301 if ( !count( $rows ) ) {
2302 return true; // nothing to do
2305 if ( !is_array( reset( $rows ) ) ) {
2309 if ( count( $uniqueIndexes ) ) {
2310 $clauses = []; // list WHERE clauses that each identify a single row
2311 foreach ( $rows as $row ) {
2312 foreach ( $uniqueIndexes as $index ) {
2313 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2314 $rowKey = []; // unique key to this row
2315 foreach ( $index as $column ) {
2316 $rowKey[$column] = $row[$column];
2318 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2321 $where = [ $this->makeList( $clauses, LIST_OR
) ];
2326 $useTrx = !$this->mTrxLevel
;
2328 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2331 # Update any existing conflicting row(s)
2332 if ( $where !== false ) {
2333 $ok = $this->update( $table, $set, $where, $fname );
2337 # Now insert any non-conflicting row(s)
2338 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2339 } catch ( Exception
$e ) {
2341 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2346 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2352 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2356 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2359 $delTable = $this->tableName( $delTable );
2360 $joinTable = $this->tableName( $joinTable );
2361 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2362 if ( $conds != '*' ) {
2363 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2367 $this->query( $sql, $fname );
2371 * Returns the size of a text field, or -1 for "unlimited"
2373 * @param string $table
2374 * @param string $field
2377 public function textFieldSize( $table, $field ) {
2378 $table = $this->tableName( $table );
2379 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2380 $res = $this->query( $sql, __METHOD__
);
2381 $row = $this->fetchObject( $res );
2385 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2395 * A string to insert into queries to show that they're low-priority, like
2396 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2397 * string and nothing bad should happen.
2399 * @return string Returns the text of the low priority option if it is
2400 * supported, or a blank string otherwise
2402 public function lowPriorityOption() {
2406 public function delete( $table, $conds, $fname = __METHOD__
) {
2408 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2411 $table = $this->tableName( $table );
2412 $sql = "DELETE FROM $table";
2414 if ( $conds != '*' ) {
2415 if ( is_array( $conds ) ) {
2416 $conds = $this->makeList( $conds, LIST_AND
);
2418 $sql .= ' WHERE ' . $conds;
2421 return $this->query( $sql, $fname );
2424 public function insertSelect(
2425 $destTable, $srcTable, $varMap, $conds,
2426 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2428 if ( $this->cliMode
) {
2429 // For massive migrations with downtime, we don't want to select everything
2430 // into memory and OOM, so do all this native on the server side if possible.
2431 return $this->nativeInsertSelect(
2442 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2443 // on only the master (without needing row-based-replication). It also makes it easy to
2444 // know how big the INSERT is going to be.
2446 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2447 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2449 $selectOptions[] = 'FOR UPDATE';
2450 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2456 foreach ( $res as $row ) {
2457 $rows[] = (array)$row;
2460 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2463 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2464 $fname = __METHOD__
,
2465 $insertOptions = [], $selectOptions = []
2467 $destTable = $this->tableName( $destTable );
2469 if ( !is_array( $insertOptions ) ) {
2470 $insertOptions = [ $insertOptions ];
2473 $insertOptions = $this->makeInsertOptions( $insertOptions );
2475 if ( !is_array( $selectOptions ) ) {
2476 $selectOptions = [ $selectOptions ];
2479 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2482 if ( is_array( $srcTable ) ) {
2483 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2485 $srcTable = $this->tableName( $srcTable );
2488 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2489 " SELECT $startOpts " . implode( ',', $varMap ) .
2490 " FROM $srcTable $useIndex $ignoreIndex ";
2492 if ( $conds != '*' ) {
2493 if ( is_array( $conds ) ) {
2494 $conds = $this->makeList( $conds, LIST_AND
);
2496 $sql .= " WHERE $conds";
2499 $sql .= " $tailOpts";
2501 return $this->query( $sql, $fname );
2505 * Construct a LIMIT query with optional offset. This is used for query
2506 * pages. The SQL should be adjusted so that only the first $limit rows
2507 * are returned. If $offset is provided as well, then the first $offset
2508 * rows should be discarded, and the next $limit rows should be returned.
2509 * If the result of the query is not ordered, then the rows to be returned
2510 * are theoretically arbitrary.
2512 * $sql is expected to be a SELECT, if that makes a difference.
2514 * The version provided by default works in MySQL and SQLite. It will very
2515 * likely need to be overridden for most other DBMSes.
2517 * @param string $sql SQL query we will append the limit too
2518 * @param int $limit The SQL limit
2519 * @param int|bool $offset The SQL offset (default false)
2520 * @throws DBUnexpectedError
2523 public function limitResult( $sql, $limit, $offset = false ) {
2524 if ( !is_numeric( $limit ) ) {
2525 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2528 return "$sql LIMIT "
2529 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2533 public function unionSupportsOrderAndLimit() {
2534 return true; // True for almost every DB supported
2537 public function unionQueries( $sqls, $all ) {
2538 $glue = $all ?
') UNION ALL (' : ') UNION (';
2540 return '(' . implode( $glue, $sqls ) . ')';
2543 public function conditional( $cond, $trueVal, $falseVal ) {
2544 if ( is_array( $cond ) ) {
2545 $cond = $this->makeList( $cond, LIST_AND
);
2548 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2551 public function strreplace( $orig, $old, $new ) {
2552 return "REPLACE({$orig}, {$old}, {$new})";
2555 public function getServerUptime() {
2559 public function wasDeadlock() {
2563 public function wasLockTimeout() {
2567 public function wasErrorReissuable() {
2571 public function wasReadOnlyError() {
2576 * Determines if the given query error was a connection drop
2579 * @param integer|string $errno
2582 public function wasConnectionError( $errno ) {
2587 * Perform a deadlock-prone transaction.
2589 * This function invokes a callback function to perform a set of write
2590 * queries. If a deadlock occurs during the processing, the transaction
2591 * will be rolled back and the callback function will be called again.
2593 * Avoid using this method outside of Job or Maintenance classes.
2596 * $dbw->deadlockLoop( callback, ... );
2598 * Extra arguments are passed through to the specified callback function.
2599 * This method requires that no transactions are already active to avoid
2600 * causing premature commits or exceptions.
2602 * Returns whatever the callback function returned on its successful,
2603 * iteration, or false on error, for example if the retry limit was
2607 * @throws DBUnexpectedError
2610 public function deadlockLoop() {
2611 $args = func_get_args();
2612 $function = array_shift( $args );
2613 $tries = self
::DEADLOCK_TRIES
;
2615 $this->begin( __METHOD__
);
2618 /** @var Exception $e */
2622 $retVal = call_user_func_array( $function, $args );
2624 } catch ( DBQueryError
$e ) {
2625 if ( $this->wasDeadlock() ) {
2626 // Retry after a randomized delay
2627 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2629 // Throw the error back up
2633 } while ( --$tries > 0 );
2635 if ( $tries <= 0 ) {
2636 // Too many deadlocks; give up
2637 $this->rollback( __METHOD__
);
2640 $this->commit( __METHOD__
);
2646 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2647 # Real waits are implemented in the subclass.
2651 public function getSlavePos() {
2656 public function getMasterPos() {
2661 public function serverIsReadOnly() {
2665 final public function onTransactionResolution( callable
$callback ) {
2666 if ( !$this->mTrxLevel
) {
2667 throw new DBUnexpectedError( $this, "No transaction is active." );
2669 $this->mTrxEndCallbacks
[] = [ $callback, wfGetCaller() ];
2672 final public function onTransactionIdle( callable
$callback ) {
2673 $this->mTrxIdleCallbacks
[] = [ $callback, wfGetCaller() ];
2674 if ( !$this->mTrxLevel
) {
2675 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2679 final public function onTransactionPreCommitOrIdle( callable
$callback ) {
2680 if ( $this->mTrxLevel
) {
2681 $this->mTrxPreCommitCallbacks
[] = [ $callback, wfGetCaller() ];
2683 // If no transaction is active, then make one for this callback
2684 $this->startAtomic( __METHOD__
);
2686 call_user_func( $callback );
2687 $this->endAtomic( __METHOD__
);
2688 } catch ( Exception
$e ) {
2689 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2695 final public function setTransactionListener( $name, callable
$callback = null ) {
2697 $this->mTrxRecurringCallbacks
[$name] = [ $callback, wfGetCaller() ];
2699 unset( $this->mTrxRecurringCallbacks
[$name] );
2704 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2706 * This method should not be used outside of Database/LoadBalancer
2708 * @param bool $suppress
2711 final public function setTrxEndCallbackSuppression( $suppress ) {
2712 $this->mTrxEndCallbacksSuppressed
= $suppress;
2716 * Actually run and consume any "on transaction idle/resolution" callbacks.
2718 * This method should not be used outside of Database/LoadBalancer
2720 * @param integer $trigger IDatabase::TRIGGER_* constant
2724 public function runOnTransactionIdleCallbacks( $trigger ) {
2725 if ( $this->mTrxEndCallbacksSuppressed
) {
2729 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2730 /** @var Exception $e */
2731 $e = null; // first exception
2732 do { // callbacks may add callbacks :)
2733 $callbacks = array_merge(
2734 $this->mTrxIdleCallbacks
,
2735 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2737 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2738 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2739 foreach ( $callbacks as $callback ) {
2741 list( $phpCallback ) = $callback;
2742 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2743 call_user_func_array( $phpCallback, [ $trigger ] );
2745 $this->setFlag( DBO_TRX
); // restore automatic begin()
2747 $this->clearFlag( DBO_TRX
); // restore auto-commit
2749 } catch ( Exception
$ex ) {
2750 call_user_func( $this->errorLogger
, $ex );
2752 // Some callbacks may use startAtomic/endAtomic, so make sure
2753 // their transactions are ended so other callbacks don't fail
2754 if ( $this->trxLevel() ) {
2755 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2759 } while ( count( $this->mTrxIdleCallbacks
) );
2761 if ( $e instanceof Exception
) {
2762 throw $e; // re-throw any first exception
2767 * Actually run and consume any "on transaction pre-commit" callbacks.
2769 * This method should not be used outside of Database/LoadBalancer
2774 public function runOnTransactionPreCommitCallbacks() {
2775 $e = null; // first exception
2776 do { // callbacks may add callbacks :)
2777 $callbacks = $this->mTrxPreCommitCallbacks
;
2778 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2779 foreach ( $callbacks as $callback ) {
2781 list( $phpCallback ) = $callback;
2782 call_user_func( $phpCallback );
2783 } catch ( Exception
$ex ) {
2784 call_user_func( $this->errorLogger
, $ex );
2788 } while ( count( $this->mTrxPreCommitCallbacks
) );
2790 if ( $e instanceof Exception
) {
2791 throw $e; // re-throw any first exception
2796 * Actually run any "transaction listener" callbacks.
2798 * This method should not be used outside of Database/LoadBalancer
2800 * @param integer $trigger IDatabase::TRIGGER_* constant
2804 public function runTransactionListenerCallbacks( $trigger ) {
2805 if ( $this->mTrxEndCallbacksSuppressed
) {
2809 /** @var Exception $e */
2810 $e = null; // first exception
2812 foreach ( $this->mTrxRecurringCallbacks
as $callback ) {
2814 list( $phpCallback ) = $callback;
2815 $phpCallback( $trigger, $this );
2816 } catch ( Exception
$ex ) {
2817 call_user_func( $this->errorLogger
, $ex );
2822 if ( $e instanceof Exception
) {
2823 throw $e; // re-throw any first exception
2827 final public function startAtomic( $fname = __METHOD__
) {
2828 if ( !$this->mTrxLevel
) {
2829 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2830 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2831 // in all changes being in one transaction to keep requests transactional.
2832 if ( !$this->getFlag( DBO_TRX
) ) {
2833 $this->mTrxAutomaticAtomic
= true;
2837 $this->mTrxAtomicLevels
[] = $fname;
2840 final public function endAtomic( $fname = __METHOD__
) {
2841 if ( !$this->mTrxLevel
) {
2842 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2844 if ( !$this->mTrxAtomicLevels ||
2845 array_pop( $this->mTrxAtomicLevels
) !== $fname
2847 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2850 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2851 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2855 final public function doAtomicSection( $fname, callable
$callback ) {
2856 $this->startAtomic( $fname );
2858 $res = call_user_func_array( $callback, [ $this, $fname ] );
2859 } catch ( Exception
$e ) {
2860 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2863 $this->endAtomic( $fname );
2868 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2869 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2870 if ( $this->mTrxLevel
) {
2871 if ( $this->mTrxAtomicLevels
) {
2872 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2873 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2874 throw new DBUnexpectedError( $this, $msg );
2875 } elseif ( !$this->mTrxAutomatic
) {
2876 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2877 throw new DBUnexpectedError( $this, $msg );
2879 // @TODO: make this an exception at some point
2880 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2881 $this->queryLogger
->error( $msg );
2882 return; // join the main transaction set
2884 } elseif ( $this->getFlag( DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2885 // @TODO: make this an exception at some point
2886 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2887 $this->queryLogger
->error( $msg );
2888 return; // let any writes be in the main transaction
2891 // Avoid fatals if close() was called
2892 $this->assertOpen();
2894 $this->doBegin( $fname );
2895 $this->mTrxTimestamp
= microtime( true );
2896 $this->mTrxFname
= $fname;
2897 $this->mTrxDoneWrites
= false;
2898 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2899 $this->mTrxAutomaticAtomic
= false;
2900 $this->mTrxAtomicLevels
= [];
2901 $this->mTrxShortId
= wfRandomString( 12 );
2902 $this->mTrxWriteDuration
= 0.0;
2903 $this->mTrxWriteQueryCount
= 0;
2904 $this->mTrxWriteAdjDuration
= 0.0;
2905 $this->mTrxWriteAdjQueryCount
= 0;
2906 $this->mTrxWriteCallers
= [];
2907 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2908 // Get an estimate of the replica DB lag before then, treating estimate staleness
2909 // as lag itself just to be safe
2910 $status = $this->getApproximateLagStatus();
2911 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2915 * Issues the BEGIN command to the database server.
2917 * @see DatabaseBase::begin()
2918 * @param string $fname
2920 protected function doBegin( $fname ) {
2921 $this->query( 'BEGIN', $fname );
2922 $this->mTrxLevel
= 1;
2925 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2926 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2927 // There are still atomic sections open. This cannot be ignored
2928 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2929 throw new DBUnexpectedError(
2931 "$fname: Got COMMIT while atomic sections $levels are still open."
2935 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2936 if ( !$this->mTrxLevel
) {
2937 return; // nothing to do
2938 } elseif ( !$this->mTrxAutomatic
) {
2939 throw new DBUnexpectedError(
2941 "$fname: Flushing an explicit transaction, getting out of sync."
2945 if ( !$this->mTrxLevel
) {
2946 $this->queryLogger
->error( "$fname: No transaction to commit, something got out of sync." );
2947 return; // nothing to do
2948 } elseif ( $this->mTrxAutomatic
) {
2949 // @TODO: make this an exception at some point
2950 $msg = "$fname: Explicit commit of implicit transaction.";
2951 $this->queryLogger
->error( $msg );
2952 return; // wait for the main transaction set commit round
2956 // Avoid fatals if close() was called
2957 $this->assertOpen();
2959 $this->runOnTransactionPreCommitCallbacks();
2960 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
2961 $this->doCommit( $fname );
2962 if ( $this->mTrxDoneWrites
) {
2963 $this->mDoneWrites
= microtime( true );
2964 $this->trxProfiler
->transactionWritingOut(
2965 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2968 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
2969 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
2973 * Issues the COMMIT command to the database server.
2975 * @see DatabaseBase::commit()
2976 * @param string $fname
2978 protected function doCommit( $fname ) {
2979 if ( $this->mTrxLevel
) {
2980 $this->query( 'COMMIT', $fname );
2981 $this->mTrxLevel
= 0;
2985 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2986 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2987 if ( !$this->mTrxLevel
) {
2988 return; // nothing to do
2991 if ( !$this->mTrxLevel
) {
2992 $this->queryLogger
->error(
2993 "$fname: No transaction to rollback, something got out of sync." );
2994 return; // nothing to do
2995 } elseif ( $this->getFlag( DBO_TRX
) ) {
2996 throw new DBUnexpectedError(
2998 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
3003 // Avoid fatals if close() was called
3004 $this->assertOpen();
3006 $this->doRollback( $fname );
3007 $this->mTrxAtomicLevels
= [];
3008 if ( $this->mTrxDoneWrites
) {
3009 $this->trxProfiler
->transactionWritingOut(
3010 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3013 $this->mTrxIdleCallbacks
= []; // clear
3014 $this->mTrxPreCommitCallbacks
= []; // clear
3015 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3016 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3020 * Issues the ROLLBACK command to the database server.
3022 * @see DatabaseBase::rollback()
3023 * @param string $fname
3025 protected function doRollback( $fname ) {
3026 if ( $this->mTrxLevel
) {
3027 # Disconnects cause rollback anyway, so ignore those errors
3028 $ignoreErrors = true;
3029 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3030 $this->mTrxLevel
= 0;
3034 public function flushSnapshot( $fname = __METHOD__
) {
3035 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3036 // This only flushes transactions to clear snapshots, not to write data
3037 throw new DBUnexpectedError(
3039 "$fname: Cannot COMMIT to clear snapshot because writes are pending."
3043 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3046 public function explicitTrxActive() {
3047 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
3051 * Creates a new table with structure copied from existing table
3052 * Note that unlike most database abstraction functions, this function does not
3053 * automatically append database prefix, because it works at a lower
3054 * abstraction level.
3055 * The table names passed to this function shall not be quoted (this
3056 * function calls addIdentifierQuotes when needed).
3058 * @param string $oldName Name of table whose structure should be copied
3059 * @param string $newName Name of table to be created
3060 * @param bool $temporary Whether the new table should be temporary
3061 * @param string $fname Calling function name
3062 * @throws RuntimeException
3063 * @return bool True if operation was successful
3065 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3068 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3071 function listTables( $prefix = null, $fname = __METHOD__
) {
3072 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3076 * Reset the views process cache set by listViews()
3079 final public function clearViewsCache() {
3080 $this->allViews
= null;
3084 * Lists all the VIEWs in the database
3086 * For caching purposes the list of all views should be stored in
3087 * $this->allViews. The process cache can be cleared with clearViewsCache()
3089 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3090 * @param string $fname Name of calling function
3091 * @throws RuntimeException
3095 public function listViews( $prefix = null, $fname = __METHOD__
) {
3096 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3100 * Differentiates between a TABLE and a VIEW
3102 * @param string $name Name of the database-structure to test.
3103 * @throws RuntimeException
3107 public function isView( $name ) {
3108 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3111 public function timestamp( $ts = 0 ) {
3112 return wfTimestamp( TS_MW
, $ts );
3115 public function timestampOrNull( $ts = null ) {
3116 if ( is_null( $ts ) ) {
3119 return $this->timestamp( $ts );
3124 * Take the result from a query, and wrap it in a ResultWrapper if
3125 * necessary. Boolean values are passed through as is, to indicate success
3126 * of write queries or failure.
3128 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3129 * resource, and it was necessary to call this function to convert it to
3130 * a wrapper. Nowadays, raw database objects are never exposed to external
3131 * callers, so this is unnecessary in external code.
3133 * @param bool|ResultWrapper|resource|object $result
3134 * @return bool|ResultWrapper
3136 protected function resultObject( $result ) {
3139 } elseif ( $result instanceof ResultWrapper
) {
3141 } elseif ( $result === true ) {
3142 // Successful write query
3145 return new ResultWrapper( $this, $result );
3149 public function ping( &$rtt = null ) {
3150 // Avoid hitting the server if it was hit recently
3151 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3152 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
3153 $rtt = $this->mRTTEstimate
;
3154 return true; // don't care about $rtt
3158 // This will reconnect if possible or return false if not
3159 $this->clearFlag( DBO_TRX
, self
::REMEMBER_PRIOR
);
3160 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3161 $this->restoreFlags( self
::RESTORE_PRIOR
);
3164 $rtt = $this->mRTTEstimate
;
3173 protected function reconnect() {
3174 $this->closeConnection();
3175 $this->mOpened
= false;
3176 $this->mConn
= false;
3178 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3179 $this->lastPing
= microtime( true );
3181 } catch ( DBConnectionError
$e ) {
3188 public function getSessionLagStatus() {
3189 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3193 * Get the replica DB lag when the current transaction started
3195 * This is useful when transactions might use snapshot isolation
3196 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3197 * is this lag plus transaction duration. If they don't, it is still
3198 * safe to be pessimistic. This returns null if there is no transaction.
3200 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3203 public function getTransactionLagStatus() {
3204 return $this->mTrxLevel
3205 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
3210 * Get a replica DB lag estimate for this server
3212 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3215 public function getApproximateLagStatus() {
3217 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3218 'since' => microtime( true )
3223 * Merge the result of getSessionLagStatus() for several DBs
3224 * using the most pessimistic values to estimate the lag of
3225 * any data derived from them in combination
3227 * This is information is useful for caching modules
3229 * @see WANObjectCache::set()
3230 * @see WANObjectCache::getWithSetCallback()
3232 * @param IDatabase $db1
3233 * @param IDatabase ...
3234 * @return array Map of values:
3235 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3236 * - since: oldest UNIX timestamp of any of the DB lag estimates
3237 * - pending: whether any of the DBs have uncommitted changes
3240 public static function getCacheSetOptions( IDatabase
$db1 ) {
3241 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3242 foreach ( func_get_args() as $db ) {
3243 /** @var IDatabase $db */
3244 $status = $db->getSessionLagStatus();
3245 if ( $status['lag'] === false ) {
3246 $res['lag'] = false;
3247 } elseif ( $res['lag'] !== false ) {
3248 $res['lag'] = max( $res['lag'], $status['lag'] );
3250 $res['since'] = min( $res['since'], $status['since'] );
3251 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3257 public function getLag() {
3261 function maxListLen() {
3265 public function encodeBlob( $b ) {
3269 public function decodeBlob( $b ) {
3270 if ( $b instanceof Blob
) {
3276 public function setSessionOptions( array $options ) {
3280 * Read and execute SQL commands from a file.
3282 * Returns true on success, error string or exception on failure (depending
3283 * on object's error ignore settings).
3285 * @param string $filename File name to open
3286 * @param bool|callable $lineCallback Optional function called before reading each line
3287 * @param bool|callable $resultCallback Optional function called for each MySQL result
3288 * @param bool|string $fname Calling function name or false if name should be
3289 * generated dynamically using $filename
3290 * @param bool|callable $inputCallback Optional function called for each
3291 * complete line sent
3292 * @return bool|string
3295 public function sourceFile(
3296 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3298 MediaWiki\
suppressWarnings();
3299 $fp = fopen( $filename, 'r' );
3300 MediaWiki\restoreWarnings
();
3302 if ( false === $fp ) {
3303 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3307 $fname = __METHOD__
. "( $filename )";
3311 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3312 } catch ( Exception
$e ) {
3322 public function setSchemaVars( $vars ) {
3323 $this->mSchemaVars
= $vars;
3327 * Read and execute commands from an open file handle.
3329 * Returns true on success, error string or exception on failure (depending
3330 * on object's error ignore settings).
3332 * @param resource $fp File handle
3333 * @param bool|callable $lineCallback Optional function called before reading each query
3334 * @param bool|callable $resultCallback Optional function called for each MySQL result
3335 * @param string $fname Calling function name
3336 * @param bool|callable $inputCallback Optional function called for each complete query sent
3337 * @return bool|string
3339 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3340 $fname = __METHOD__
, $inputCallback = false
3344 while ( !feof( $fp ) ) {
3345 if ( $lineCallback ) {
3346 call_user_func( $lineCallback );
3349 $line = trim( fgets( $fp ) );
3351 if ( $line == '' ) {
3355 if ( '-' == $line[0] && '-' == $line[1] ) {
3363 $done = $this->streamStatementEnd( $cmd, $line );
3367 if ( $done ||
feof( $fp ) ) {
3368 $cmd = $this->replaceVars( $cmd );
3370 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3371 $res = $this->query( $cmd, $fname );
3373 if ( $resultCallback ) {
3374 call_user_func( $resultCallback, $res, $this );
3377 if ( false === $res ) {
3378 $err = $this->lastError();
3380 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3391 * Called by sourceStream() to check if we've reached a statement end
3393 * @param string $sql SQL assembled so far
3394 * @param string $newLine New line about to be added to $sql
3395 * @return bool Whether $newLine contains end of the statement
3397 public function streamStatementEnd( &$sql, &$newLine ) {
3398 if ( $this->delimiter
) {
3400 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3401 if ( $newLine != $prev ) {
3410 * Database independent variable replacement. Replaces a set of variables
3411 * in an SQL statement with their contents as given by $this->getSchemaVars().
3413 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3415 * - '{$var}' should be used for text and is passed through the database's
3417 * - `{$var}` should be used for identifiers (e.g. table and database names).
3418 * It is passed through the database's addIdentifierQuotes method which
3419 * can be overridden if the database uses something other than backticks.
3420 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3421 * database's tableName method.
3422 * - / *i* / passes the name that follows through the database's indexName method.
3423 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3424 * its use should be avoided. In 1.24 and older, string encoding was applied.
3426 * @param string $ins SQL statement to replace variables in
3427 * @return string The new SQL statement with variables replaced
3429 protected function replaceVars( $ins ) {
3430 $vars = $this->getSchemaVars();
3431 return preg_replace_callback(
3433 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3434 \'\{\$ (\w+) }\' | # 3. addQuotes
3435 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3436 /\*\$ (\w+) \*/ # 5. leave unencoded
3438 function ( $m ) use ( $vars ) {
3439 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3440 // check for both nonexistent keys *and* the empty string.
3441 if ( isset( $m[1] ) && $m[1] !== '' ) {
3442 if ( $m[1] === 'i' ) {
3443 return $this->indexName( $m[2] );
3445 return $this->tableName( $m[2] );
3447 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3448 return $this->addQuotes( $vars[$m[3]] );
3449 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3450 return $this->addIdentifierQuotes( $vars[$m[4]] );
3451 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3452 return $vars[$m[5]];
3462 * Get schema variables. If none have been set via setSchemaVars(), then
3463 * use some defaults from the current object.
3467 protected function getSchemaVars() {
3468 if ( $this->mSchemaVars
) {
3469 return $this->mSchemaVars
;
3471 return $this->getDefaultSchemaVars();
3476 * Get schema variables to use if none have been set via setSchemaVars().
3478 * Override this in derived classes to provide variables for tables.sql
3479 * and SQL patch files.
3483 protected function getDefaultSchemaVars() {
3487 public function lockIsFree( $lockName, $method ) {
3491 public function lock( $lockName, $method, $timeout = 5 ) {
3492 $this->mNamedLocksHeld
[$lockName] = 1;
3497 public function unlock( $lockName, $method ) {
3498 unset( $this->mNamedLocksHeld
[$lockName] );
3503 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3504 if ( $this->writesOrCallbacksPending() ) {
3505 // This only flushes transactions to clear snapshots, not to write data
3506 throw new DBUnexpectedError(
3508 "$fname: Cannot COMMIT to clear snapshot because writes are pending."
3512 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3516 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3517 if ( $this->trxLevel() ) {
3518 // There is a good chance an exception was thrown, causing any early return
3519 // from the caller. Let any error handler get a chance to issue rollback().
3520 // If there isn't one, let the error bubble up and trigger server-side rollback.
3521 $this->onTransactionResolution( function () use ( $lockKey, $fname ) {
3522 $this->unlock( $lockKey, $fname );
3525 $this->unlock( $lockKey, $fname );
3529 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
3534 public function namedLocksEnqueue() {
3539 * Lock specific tables
3541 * @param array $read Array of tables to lock for read access
3542 * @param array $write Array of tables to lock for write access
3543 * @param string $method Name of caller
3544 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3547 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3552 * Unlock specific tables
3554 * @param string $method The caller
3557 public function unlockTables( $method ) {
3563 * @param string $tableName
3564 * @param string $fName
3565 * @return bool|ResultWrapper
3568 public function dropTable( $tableName, $fName = __METHOD__
) {
3569 if ( !$this->tableExists( $tableName, $fName ) ) {
3572 $sql = "DROP TABLE " . $this->tableName( $tableName );
3573 if ( $this->cascadingDeletes() ) {
3577 return $this->query( $sql, $fName );
3581 * Get search engine class. All subclasses of this need to implement this
3582 * if they wish to use searching.
3586 public function getSearchEngine() {
3587 return 'SearchEngineDummy';
3590 public function getInfinity() {
3594 public function encodeExpiry( $expiry ) {
3595 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3596 ?
$this->getInfinity()
3597 : $this->timestamp( $expiry );
3600 public function decodeExpiry( $expiry, $format = TS_MW
) {
3601 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3603 : wfTimestamp( $format, $expiry );
3606 public function setBigSelects( $value = true ) {
3610 public function isReadOnly() {
3611 return ( $this->getReadOnlyReason() !== false );
3615 * @return string|bool Reason this DB is read-only or false if it is not
3617 protected function getReadOnlyReason() {
3618 $reason = $this->getLBInfo( 'readOnlyReason' );
3620 return is_string( $reason ) ?
$reason : false;
3623 public function setTableAliases( array $aliases ) {
3624 $this->tableAliases
= $aliases;
3631 public function __toString() {
3632 return (string)$this->mConn
;
3636 * Run a few simple sanity checks
3638 public function __destruct() {
3639 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3640 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3642 $danglingCallbacks = array_merge(
3643 $this->mTrxIdleCallbacks
,
3644 $this->mTrxPreCommitCallbacks
,
3645 $this->mTrxEndCallbacks
3647 if ( $danglingCallbacks ) {
3649 foreach ( $danglingCallbacks as $callbackInfo ) {
3650 $callers[] = $callbackInfo[1];
3652 $callers = implode( ', ', $callers );
3653 trigger_error( "DB transaction callbacks still pending (from $callers)." );
3661 abstract class Database
extends DatabaseBase
{
3662 // B/C until nothing type hints for DatabaseBase
3663 // @TODO: finish renaming DatabaseBase => Database